﻿using System;
using System.Collections.Generic;
using System.Text;
using ExpressionUtil.Common;

namespace ExpressionUtil.Parser.Handler
{
    internal class BracketPairHandler : ParseHandlerBase
    {
        public BracketPairHandler()
        {
            this.next = new CommaHandler();
        }

        /// <summary>
        /// 解析元素
        /// </summary>
        /// <param name="context">解析参数</param>
        /// <param name="element">需要解析的元素</param>
        /// <returns>是否已解析</returns>
        protected override bool ParseCore(string element, ParseContext context)
        {
            bool ret = false;
            if (element == ")")
            {
                this.ParseBracketPair(context);
                ret = true;
            }
            return ret;
        }

        private void ParseBracketPair(ParseContext context)
        {
            while (context.OperatorStack.Count > 0)
            {
                string op = context.OperatorStack.Pop();
                if (op == "(")
                {
                    return;
                }
                else if (op.EndsWith("("))
                {
                    op = "Function_" + op.ToLower();
                }
                CheckHelper.CreateHandlerExists(op, "Unknow operator/function or missing left bracket.");
                if (ParseContext.ExtFunctionMap.ContainsKey(op))
                {
                    context.CurrentExtFunctionName = op;
                }
                ParseContext.CreateHandlerMap[op](context);
                if (op.StartsWith("Function_"))
                {
                    this.PopFunctionParameterCountStack(context);
                    return;
                }
            }
            throw new FormatException("Missing left bracket.");
        }

        private void PopFunctionParameterCountStack(ParseContext context)
        {
            context.FunctionParameterCount.Pop();
            context.IncreaseFunctionParameterCount();
        }
    }
}
